package kata18;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TransitiveDependencies {
    private Map<String, Set<String>> repository;

    public TransitiveDependencies() {
        repository = new HashMap<>();
    }
    public void addDependencies(String source, String dependencies) {
        List<String> dependenice = Stream.of(dependencies.split(" "))
                .collect(Collectors.toList());
        putDependencies(source,dependenice);
    }

    public void putDependencies(String source,List<String> dependenice){
        //先获取
        Set<String> dependeniceSet = repository.get(source);
        //为空则新建
        if(dependeniceSet == null){
            dependeniceSet = new HashSet<>(dependenice);
        }

        dependeniceSet.addAll(dependenice);
        repository.put(source,dependeniceSet);
    }

    /**
     * 通过输入值，获取期望值
     *
     * @param source 输入值
     * @return 期望值
     */
    public String getAllDependencies(String source) {
        Set<String> result = new HashSet<>();
        getAllDependencies(source,result);
        return result.stream().filter(str -> !source.equals(str)).collect(Collectors.joining(" "));
    }

    private void getAllDependencies(String source,Set<String> result) {
        Set<String> set = repository.get(source);
        if(set == null || set.size() == 0){
            return;
        }
        //数组拷贝
        List<String> setCopy = new ArrayList<>(set);
        //移除已处理的数据
        setCopy.removeAll(result);
        if(setCopy == null || setCopy.size() == 0){
            return;
        }

        //加入未处理的数据
        result.addAll(setCopy);
        for (String dependenice :setCopy) {
            //递归调用
            getAllDependencies(dependenice,result);
        }
    }
}
